#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPIP.
#    COOPIP is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPIP is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPIP.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
IncludePath="/opt/coopip/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopip/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
import CIS, AMR, OMS, GIS
from django.contrib.gis.db import models
#********************Setup psycopg2 and django section********************
from django.db import transaction

import urllib
import httplib
import datetime
import ftplib
import telnetlib

LocalFilePath='/opt/coopip/outgoingftp/'
LocalFileName='MeterInfoUpdate.txt'
RemoteFileName='workfile/meterfil'
#FTPLoginUsername='casystem'
#FTPLoginPassword='Siren20!'
FTPLoginUsername='preview'
FTPLoginPassword='Dream35.'
FTPServer='192.168.100.1'
TelnetLoginUsername=FTPLoginUsername
TelnetLoginPassword=FTPLoginPassword
TelnetServer=FTPServer

def GenerateBatchFile(MeterNumbers):
    for meterNumber in MeterNumbers:
        meter = CIS.Meterdetl.objects.filter()

CISMeters=list(CIS.Meterdetl.objects.filter(deletecode='00').filter(junkedcode='00'))
RecentCISMeters=[]
for i in CISMeters:
    if(int(i.purchdate[:2]) > 12 and int(i.purchdate[:2]) < 50):
        RecentCISMeters.append(i)


UpdateStrings = []
for i in RecentCISMeters:
    if(i.serial.lstrip('0').strip() in i.amrid):
        print "Skipping:  " + str(i.serial).ljust(25) + str(i.amrid).ljust(25)
        continue
    UpdateString = ''
    UpdateString = UpdateString + i.meter #Pos 1-12, Meter Number, Length 12
    UpdateString = UpdateString + i.serial #Pos 13-32, Serial Number, Length 20
    UpdateString = UpdateString + '000.00' #Pos 33-38, Full Load Test Default to 0's, See if needed, Length 6
    UpdateString = UpdateString + '000.00' #Pos 39-44, Power Factor Test Default to 0's, See if needed, Length 6
    UpdateString = UpdateString + '000.00' #Pos 45-50, Power Factor Test Default to 0's, See if needed, Length 6
    #UpdateString = UpdateString + '02' + str(i.serial).lstrip('0').strip().ljust(18, '0') #Pos 51-70, AMRVendor + AMRID, Left Justify, Trailing Spaces, Length 20
    UpdateString = UpdateString + str(i.serial).lstrip('0').strip().ljust(20, ' ') #Pos 51-70, AMRVendor + AMRID, Left Justify, Trailing Spaces, Length 20

    UpdateString = UpdateString + '9' + '\n'
    UpdateStrings.append(UpdateString)
    print "Updating:  " + str(i.serial).ljust(25) + str(i.amrid).ljust(25)




def CreateLocalMeterInfoUpdateFile(UpdateStrings):
    OutputFile=open(LocalFilePath + LocalFileName, 'w')
    OutputFile.writelines(UpdateStrings)
    OutputFile.close()

def Upload(ftp):
    ext = os.path.splitext(LocalFileName)[1]    
    if ext in (".txt", ".htm", ".html"):
        LocalFile=open(LocalFilePath + LocalFileName, 'r')
        ftp.storlines("STOR " + RemoteFileName, LocalFile)
    else:
        LocalFile=open(LocalFilePath + LocalFileName, 'rb')
        ftp.storbinary("STOR " + RemoteFileName, LocalFile, 1024)
    LocalFile.close()



CreateLocalMeterInfoUpdateFile(UpdateStrings)

ftp = ftplib.FTP(FTPServer)
ftp.login(FTPLoginUsername , FTPLoginPassword)
Upload(ftp)

telnet=telnetlib.Telnet(TelnetServer)
telnet.set_debuglevel(2)

telnet.read_until("login: ")
telnet.write(TelnetLoginUsername + "\n")
telnet.read_until("Password: ")
telnet.write(TelnetLoginPassword + "\n")
telnet.read_until("$")
telnet.write("run pub/addmeter\n")
telnet.read_until("EXISTING METERS.")
telnet.write("U\n")
telnet.read_until("Y/N")
telnet.write("N\n") #Do you want to update a specific field
telnet.read_until("Y/N")
telnet.write("N\n") #Do you want to post test data
telnet.read_until("3=REGULAR METER")
telnet.write("1\n") #1= AMR Meter
telnet.read_until("'04' = CARINA.")
telnet.write("02\n") #'02' = DCSI
telnet.read_until("CORRECT? Y/N/E")
telnet.write("Y\n") #Yes, all above answers are correct


telnet.read_until("$")
telnet.write("exit\n")
print telnet.read_all()


